package design.patterns.proxyMode.vectorproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Vector;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2020/6/10 19:47
 */

public class VectorProxy implements InvocationHandler {

    private Object proxyobj;

    public VectorProxy(Object proxyobj) {
        this.proxyobj = proxyobj;
    }

    /**
     * 静态工厂方法,这是个简单工厂模式
     * @param obj
     * @return
     */
    public static Object factory(Object obj){
        Class cls = obj.getClass();
        return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(), new VectorProxy(obj));
    }

    /**
     * 调用目标某个方法，被 InvocationHandler 拦截
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before calling " + method);

        Object obj = method.invoke(proxyobj, args);
        System.out.println("after calling " + method);
        return obj;
    }


    public static void main(String[] args) {
        List v = null;
        v = (List) VectorProxy.factory(new Vector<List>(10));
        v.add("sss");
        v.get(0);

    }
}
